package com.jdchain.samples.rest.config;

import com.jd.blockchain.crypto.Crypto;
import com.jd.blockchain.crypto.HashDigest;
import com.jd.blockchain.crypto.KeyGenUtils;
import com.jd.blockchain.crypto.PrivKey;
import com.jd.blockchain.crypto.PubKey;
import com.jd.blockchain.ledger.BlockchainKeypair;
import com.jd.blockchain.sdk.BlockchainService;
import com.jd.blockchain.sdk.client.GatewayServiceFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import utils.codec.Base58Utils;
import utils.net.NetworkAddress;

/**
 * JDChain 配置类
 */
@Configuration
public class JdChainConfig {

    @Value("${jdchain.gateway.host:127.0.0.1}")
    private String gatewayHost;

    @Value("${jdchain.gateway.port:11000}")
    private int gatewayPort;

    @Value("${jdchain.ledger.hash}")
    private String ledgerHashString;

    @Value("${jdchain.admin.pubkey}")
    private String adminPubKeyString;

    @Value("${jdchain.admin.privkey}")
    private String adminPrivKeyString;

    @Value("${jdchain.admin.password}")
    private String adminPassWordtring;

    @Value("${jdchain.contract.address}")
    private String contractAddress;

    @Value("${jdchain.data.account.address}")
    private String dataAccountAddress;

    /**
     * 创建区块链服务
     */
    @Bean
    public BlockchainService blockchainService() {
        GatewayServiceFactory serviceFactory = GatewayServiceFactory.connect(gatewayHost,gatewayPort,false,adminKeypair());
        return serviceFactory.getBlockchainService();
    }

    /**
     * 获取账本哈希
     */
    @Bean
    public HashDigest ledgerHash() {
        return Crypto.resolveAsHashDigest(Base58Utils.decode(ledgerHashString));
    }

    /**
     * 获取管理员密钥对
     */
    @Bean
    public BlockchainKeypair adminKeypair() {
        // 去除可能存在的空格
        String pubKeyStr = adminPubKeyString.trim();
        String privKeyStr = adminPrivKeyString.trim();
        String passwordStr = adminPassWordtring.trim();
        
        System.out.println("公钥值: [" + pubKeyStr + "]");
        System.out.println("私钥值: [" + privKeyStr + "]");
        System.out.println("密码值: [" + passwordStr + "]");
        
        PubKey pubKey = KeyGenUtils.decodePubKey(pubKeyStr);
        // 简化私钥解码，使用默认算法
        PrivKey privKey = KeyGenUtils.decodePrivKey(privKeyStr, passwordStr);
        return new BlockchainKeypair(pubKey, privKey);
    }

    /**
     * 获取合约地址
     */
    @Bean
    public String contractAddress() {
        return contractAddress;
    }

    /**
     * 获取数据账户地址
     */
    @Bean
    public String dataAccountAddress() {
        return dataAccountAddress;
    }
}

